package com.beiding.delaytask.fram;

import lombok.Builder;
import lombok.Data;
import org.quartz.CronExpression;

import java.text.ParseException;
import java.util.Date;

/**
 * @author 丁常磊
 * @date 2021/8/13 13:25
 */

@Data
@Builder
public class Time {
    /**
     * 天
     */
    private int day;

    /**
     * 小时
     */
    private int hour;

    /**
     * 分钟
     */
    private int minute;

    /**
     * 秒数
     */
    private int second;

    public int toSeconds() {
        return day * DD + hour * HH + minute * MI + second;
    }


    public static final int MI = 60;
    public static final int HH = MI * 60;
    public static final int DD = HH * 24;

    /**
     * 将秒数转date
     * @param seconds
     * @return
     */
    public static Time toTime(int seconds) {

        //天
        int day = seconds / DD;
        int dx = seconds - day * DD;

        //小时
        int hour = dx / HH;
        int hx = dx - hour * HH;

        //分钟
        int minute = hx / MI;

        //秒
        int second = hx - minute * MI;

        return Time.builder().day(day).hour(hour).minute(minute).second(second).build();
    }

    /**
     * 使用cron表达式计算下次的时间戳
     *
     * @param cron
     * @param current
     * @return
     */
    public static Date nextTime(String cron, Date current) {
        try {
            CronExpression cronExpression = new CronExpression(cron);
            return cronExpression.getNextValidTimeAfter(current);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取下个时间戳
     * @param cron
     * @param current
     * @return
     */
    public static Date nextTime(String cron, long current) {
        return nextTime(cron, new Date(current));
    }

    /**
     * 相对当前时间计算下一个时间
     * @param cron
     * @return
     */
    public static Date nextTime(String cron) {
        return nextTime(cron, new Date());
    }

    //使用Calendar进行时间计算

}
